import Router from 'koa-router';
import ReplyTemplateGroup from '../models/replyTemplateGroup';
import ReplyTemplate from '../models/replyTemplate';
import tokenAuth from '../middleware/tokenAuth';

const router = new Router({
  prefix: '/api/replyTemplateGroups',
});
router.use(tokenAuth());

/**
 * 新建模板组
 * input => {
 *  name:String,
 *  user_group:ObjectId/ref UserGroup
 * }
 */
router.post('/create', async (ctx /* ,next */) => {
  const input = ctx.request.body;
  const replyTemplateGroup = new ReplyTemplateGroup(input);

  await replyTemplateGroup.save();

  ctx.body = {
    ok: true,
    reply_template_group: replyTemplateGroup,
  };
});

/**
 * 更新模板组
 * id => templateGroupId
 * input => {
 *  any.
 * }
 */
router.post('/:id/update', async (ctx /* ,next */) => {
  const input = ctx.request.body;
  const replyTemplateGroupId = ctx.params.id;
  const replyTemplateGroup = await ReplyTemplateGroup.findByIdAndUpdate(
    replyTemplateGroupId,
    input,
    { new: true },
  );

  ctx.body = {
    ok: true,
    reply_template_group: replyTemplateGroup,
  };
});

/**
 * 删除模板组
 * id => templateGroupId
 */
router.post('/:id/delete', async (ctx /* ,next */) => {
  const replyTemplateGroupId = ctx.params.id;
  const replyTemplateGroup = await ReplyTemplateGroup.findByIdAndRemove(replyTemplateGroupId);
  await ReplyTemplate.remove({ template_group: replyTemplateGroup });

  ctx.body = {
    ok: true,
    reply_template_group: replyTemplateGroup,
  };
});

export default router;
